'use client';

import { useState, useEffect } from 'react';
import { useAuth } from '@/lib/auth/context';
import { MemoryType, Memory, CreateMemoryPayload } from '@/lib/api/types';
import { getMemories, createMemory, updateMemory, deleteMemory } from '@/lib/api/memory';

interface MemoryManagerProps {
  sessionId?: string;
  onMemorySelect?: (memory: any) => void;
  className?: string;
}

export function MemoryManager({ sessionId, onMemorySelect, className = "" }: MemoryManagerProps) {
  const { user } = useAuth();
  const [memories, setMemories] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedType, setSelectedType] = useState<MemoryType | ''>('');
  const [showAddForm, setShowAddForm] = useState(false);
  const [newMemory, setNewMemory] = useState({
    content: '',
    type: MemoryType.FACT,
    importance: 3,
    tags: [] as string[],
  });
  const [newTag, setNewTag] = useState('');

  const fetchMemories = async () => {
    if (!user) return;
    
    setLoading(true);
    try {
      const data = await getMemories({
        type: selectedType || undefined,
        tags: searchQuery ? [searchQuery] : undefined,
      });
      setMemories(data.memories || []);
    } catch (error) {
      console.error('Failed to get memories:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMemories();
  }, [user, sessionId, selectedType, searchQuery]);

  const handleAddMemory = async () => {
    if (!user || !newMemory.content.trim()) return;
    
    try {
      await createMemory({
        content: newMemory.content,
        type: newMemory.type,
        importance: newMemory.importance,
        tags: newMemory.tags,
      });
      
      setNewMemory({
        content: '',
        type: MemoryType.FACT,
        importance: 3,
        tags: [],
      });
      setNewTag('');
      setShowAddForm(false);
      fetchMemories();
    } catch (error) {
      console.error('Failed to add memory:', error);
    }
  };

  const handleDeleteMemory = async (memoryId: string) => {
    if (!user) return;
    
    try {
      await deleteMemory(memoryId);
      fetchMemories();
    } catch (error) {
      console.error('Failed to delete memory:', error);
    }
  };

  const handleAddTag = () => {
    if (newTag.trim() && !newMemory.tags.includes(newTag.trim())) {
      setNewMemory(prev => ({
        ...prev,
        tags: [...prev.tags, newTag.trim()]
      }));
      setNewTag('');
    }
  };

  const handleRemoveTag = (tagToRemove: string) => {
    setNewMemory(prev => ({
      ...prev,
      tags: prev.tags.filter(tag => tag !== tagToRemove)
    }));
  };

  const handleTagKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleAddTag();
    }
  };

  const getTypeColor = (type: MemoryType) => {
    switch (type) {
      case MemoryType.PREFERENCE: return 'bg-blue-100 text-blue-800';
      case MemoryType.FACT: return 'bg-green-100 text-green-800';
      case MemoryType.EMOTION: return 'bg-purple-100 text-purple-800';
      case MemoryType.GOAL: return 'bg-orange-100 text-orange-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getTypeLabel = (type: MemoryType) => {
    switch (type) {
      case MemoryType.PREFERENCE: return 'Preference';
      case MemoryType.FACT: return 'Fact';
      case MemoryType.EMOTION: return 'Emotion';
      case MemoryType.GOAL: return 'Goal';
      default: return 'Unknown';
    }
  };

  return (
    <div className={`bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 ${className}`}>
      {/* Header */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Memory Management</h3>
          <button
            onClick={() => setShowAddForm(!showAddForm)}
            className="px-3 py-1.5 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 transition-colors"
          >
            {showAddForm ? 'Cancel' : 'Add Memory'}
          </button>
        </div>

        {/* Search and filter */}
        <div className="flex gap-2 mb-3">
          <input
            type="text"
            placeholder="Search memories..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="flex-1 px-3 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
          <select
            value={selectedType}
            onChange={(e) => setSelectedType(e.target.value as MemoryType | '')}
            className="px-3 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="">All Types</option>
            <option value={MemoryType.PREFERENCE}>Preference</option>
            <option value={MemoryType.FACT}>Fact</option>
            <option value={MemoryType.EMOTION}>Emotion</option>
            <option value={MemoryType.GOAL}>Goal</option>
          </select>
        </div>

        {/* Add memory form */}
        {showAddForm && (
          <div className="p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
            <textarea
              placeholder="Enter memory content..."
              value={newMemory.content}
              onChange={(e) => setNewMemory(prev => ({ ...prev, content: e.target.value }))}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-600 text-gray-900 dark:text-white rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 mb-2"
              rows={3}
            />
            <div className="flex gap-2 mb-2">
              <select
                value={newMemory.type}
                onChange={(e) => setNewMemory(prev => ({ ...prev, type: e.target.value as MemoryType }))}
                className="px-3 py-1.5 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-600 text-gray-900 dark:text-white rounded text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value={MemoryType.PREFERENCE}>Preference</option>
                <option value={MemoryType.FACT}>Fact</option>
                <option value={MemoryType.EMOTION}>Emotion</option>
                <option value={MemoryType.GOAL}>Goal</option>
              </select>
              <select
                value={newMemory.importance}
                onChange={(e) => setNewMemory(prev => ({ ...prev, importance: parseInt(e.target.value) }))}
                className="px-3 py-1.5 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-600 text-gray-900 dark:text-white rounded text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value={1}>Importance: 1</option>
                <option value={2}>Importance: 2</option>
                <option value={3}>Importance: 3</option>
                <option value={4}>Importance: 4</option>
                <option value={5}>Importance: 5</option>
              </select>
            </div>
            
            {/* Tag input */}
            <div className="mb-2">
              <label className="text-sm text-gray-700 dark:text-gray-300 mb-1 block">Tags</label>
              <div className="flex gap-2 mb-2">
                <input
                  type="text"
                  value={newTag}
                  onChange={(e) => setNewTag(e.target.value)}
                  onKeyPress={handleTagKeyPress}
                  placeholder="Enter tag..."
                  className="flex-1 px-3 py-1.5 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-600 text-gray-900 dark:text-white rounded text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
                <button
                  type="button"
                  onClick={handleAddTag}
                  className="px-3 py-1.5 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 transition-colors"
                >
                  Add
                </button>
              </div>
              {/* Added tags */}
              {newMemory.tags.length > 0 && (
                <div className="flex flex-wrap gap-1">
                  {newMemory.tags.map((tag) => (
                    <span
                      key={tag}
                      className="inline-flex items-center gap-1 px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full"
                    >
                      {tag}
                      <button
                        type="button"
                        onClick={() => handleRemoveTag(tag)}
                        className="text-blue-600 hover:text-blue-800"
                      >
                        ×
                      </button>
                    </span>
                  ))}
                </div>
              )}
            </div>
            
            <div className="flex gap-2">
              <button
                onClick={handleAddMemory}
                className="px-3 py-1.5 bg-green-600 text-white text-sm rounded hover:bg-green-700 transition-colors"
              >
                Save
              </button>
              <button
                onClick={() => setShowAddForm(false)}
                className="px-3 py-1.5 bg-gray-500 text-white text-sm rounded hover:bg-gray-600 transition-colors"
              >
                Cancel
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Memory list */}
      <div className="p-4 max-h-96 overflow-y-auto">
        {loading ? (
          <div className="flex items-center justify-center py-8">
            <div className="w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
          </div>
        ) : memories.length === 0 ? (
          <div className="text-center py-8 text-gray-500 dark:text-gray-400">
            {searchQuery ? 'No related memories found' : 'No memories yet'}
          </div>
        ) : (
          <div className="space-y-3">
            {memories.map((memory) => (
              <div
                key={memory.id}
                className="p-3 border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-700 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors"
              >
                <div className="flex items-start justify-between mb-2">
                  <div className="flex items-center gap-2">
                    <span className={`px-2 py-1 text-xs rounded-full ${getTypeColor(memory.type)}`}>
                      {getTypeLabel(memory.type)}
                    </span>
                    <span className="text-xs text-gray-500 dark:text-gray-400">
                      Importance: {memory.importance}
                    </span>
                  </div>
                  <div className="flex gap-1">
                    {onMemorySelect && (
                      <button
                        onClick={() => onMemorySelect(memory)}
                        className="p-1 text-blue-600 hover:bg-blue-100 rounded"
                        title="Select memory"
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                        </svg>
                      </button>
                    )}
                    <button
                      onClick={() => handleDeleteMemory(memory.id)}
                      className="p-1 text-red-600 hover:bg-red-100 rounded"
                      title="Delete memory"
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                      </svg>
                    </button>
                  </div>
                </div>
                <p className="text-sm text-gray-700 dark:text-gray-300 mb-2">{memory.content}</p>
                {memory.tags && memory.tags.length > 0 && (
                  <div className="flex flex-wrap gap-1">
                    {memory.tags.map((tag: string, index: number) => (
                      <span
                        key={index}
                        className="px-2 py-0.5 bg-gray-100 dark:bg-gray-600 text-gray-600 dark:text-gray-300 text-xs rounded"
                      >
                        #{tag}
                      </span>
                    ))}
                  </div>
                )}
                <div className="text-xs text-gray-400 dark:text-gray-500 mt-2">
                  {new Date(memory.createdAt).toLocaleString()}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
